package com.aisb.core.log;

import com.aisb.core.InitParam;
import com.aisb.core.SessionBean;
import com.aisb.core.util.DateUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Description：
 * @Author wucm
 * @Date 2018/1/6
 */
@Aspect
@Component
public class LogLoginAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogLoginAspect.class);

    @Autowired
    LogDao logDao;

    @Pointcut("@annotation(com.aisb.core.log.LogLogin)")
    public void logLoginPointCut() {
    }

    @Around("logLoginPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        Map param = request.getParameterMap();

        MethodSignature sign = (MethodSignature) pjp.getSignature();
        Method method = sign.getMethod();
        LogLogin annotation = method.getAnnotation(LogLogin.class);

        Long start = System.currentTimeMillis();

        // result的值就是被拦截方法的返回值
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();
        if (null != sessionBean) {
            LogVisitBean log = new LogVisitBean();
            String logContent;
            if (null != result) {
                logContent = annotation.value() + "，耗时为：" + (System.currentTimeMillis() - start) + "ms，返回结果为：" + JSONObject.toJSON(result).toString();
            } else {
                logContent = annotation.value() + "，耗时为：" + (System.currentTimeMillis() - start) + "ms";
            }
            log.setLogContent(logContent);
            log.setUserId(sessionBean.getUserId());
            log.setUserName(sessionBean.getUserName());
            log.setLogId(sessionBean.getLogId());
            log.setLogTime(DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));
            logDao.insertVisitLog(log);
        }

        return result;
    }
}
